package com.free.semantic.core.conceptservice.impl;

import com.free.semantic.core.common.UserConceptManageInfo;
import com.free.semantic.core.conceptservice.ConceptService;
import com.free.semantic.infrastruct.repository.SemanticNetworkRepository;
import com.free.semantic.model.conceptmodel.SemanticNetwork;
import com.free.semantic.model.conceptmodel.SemanticNetworkDelta;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ConceptServiceImpl implements ConceptService {

    @Resource
    private SemanticNetworkRepository semanticNetworkRepository;

    @Value("${baseUrl}")
    private String baseUrl;

    @Override
    public SemanticNetwork save(Long userId, Long id, SemanticNetworkDelta semanticNetwork) {
        semanticNetwork.setId(id);
        semanticNetwork.setUserId(userId);
        Long saveID = semanticNetworkRepository.save(semanticNetwork);
        return semanticNetworkRepository.findById(saveID);
    }

    @Override
    public UserConceptManageInfo loadUserConcepts(Long userId) {
        List<SemanticNetwork> byUserId = semanticNetworkRepository.findByUserId(userId);
        return convert(userId, byUserId);
    }

    private UserConceptManageInfo convert(Long userId, List<SemanticNetwork> semanticNetworks) {
        UserConceptManageInfo conceptManageInfo = new UserConceptManageInfo(baseUrl, userId, (id, semanticNetwork)
                -> save(userId, semanticNetwork.getId(), semanticNetwork), id -> delete(userId, id));
        for (SemanticNetwork network : semanticNetworks) {
            conceptManageInfo.addConcept(network.getName(), network);
        }
        return conceptManageInfo;
    }

    @Override
    public void delete(Long userId, Long id) {
        semanticNetworkRepository.deleteById(id);
    }
}
